package com.jiulan.hearthearing.ui.course.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.viewpager.widget.ViewPager;

import com.aliyun.player.AliPlayer;
import com.aliyun.player.AliPlayerFactory;
import com.aliyun.player.IPlayer;
import com.aliyun.player.bean.ErrorInfo;
import com.aliyun.player.bean.InfoBean;
import com.aliyun.player.bean.InfoCode;
import com.aliyun.player.source.VidAuth;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.jiulan.hearthearing.R;
import com.jiulan.hearthearing.base.BaseActivity;
import com.jiulan.hearthearing.constants.UrlConstants;
import com.jiulan.hearthearing.http.HttpRequest;
import com.jiulan.hearthearing.http.HttpStringCallBack;
import com.jiulan.hearthearing.ui.course.fragment.CourseDetailsFMFragment;
import com.jiulan.hearthearing.ui.course.fragment.CourseDetailsHudongFragment;
import com.jiulan.hearthearing.ui.course.model.CourseDetailsModel;
import com.jiulan.hearthearing.ui.course.model.CourseDetailsPlayAuthModel;
import com.jiulan.hearthearing.ui.course.view.CoursePlayMuluSetDialog;
import com.jiulan.hearthearing.ui.course.view.CoursePlaySpeedSetDialog;
import com.jiulan.hearthearing.ui.course.view.CoursePlayTimingSetDialog;
import com.jiulan.hearthearing.utils.TimeFormater;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

public class CourseDetailsFMActivity extends BaseActivity implements View.OnClickListener {
    private int id;
    CourseDetailsFMFragment fmFragment;
    CourseDetailsHudongFragment hudongFragment;
    private CoursePagerAdapter mAdapter;
    private String[] mTitle = {"课程详情", "互动交流"};
    private AliPlayer aliyunVodPlayer;
    private CourseDetailsModel courseDetailsModel;
    private CourseDetailsPlayAuthModel model;
    //原视频的buffered
    private long mVideoBufferedPosition = 0;
    private long mCurrentPosition = 0;
    private int loop = 0;//1单曲循环,2列表循环,0顺序播放
    private float speed = 1.0f;
    private long mDuration = 0;
    private int mPosition = 0;
    private int chooseId = 0;
    private boolean isPlaying = false;

    private TextView tvTitle;
    private TextView tvShortTitle;
    private ImageView ivPlay;
    private ImageView ivDaotui;
    private ImageView ivQianjin;
    private ImageView ivXunhuan;
    private ImageView ivBeisu;
    private ImageView ivDingshi;
    private ImageView ivList;
    private ImageView ivWengao;
    private TextView tvPlayTime;
    private TextView tvTotalTime;
    private SeekBar seekBar;
    private TabLayout mTabLayout;
    private ViewPager mViewPager;

    public static void actionStart(Context context, int id) {
        Intent intent = new Intent(context, CourseDetailsFMActivity.class);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    public static LocalBroadcastManager localBroadcastManager;
    private MyBroadcastReceiver myBroadcastReceiver;
    private IntentFilter filter;
    public static String LOCAL_BROADCAST = "com.jiulan.hearthearing.ui.course.activity.CourseDetailsFMActivity";

    public void registerMessageReceiver() {
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        myBroadcastReceiver = new MyBroadcastReceiver();
        filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(LOCAL_BROADCAST);
        localBroadcastManager.registerReceiver(myBroadcastReceiver, filter);
    }

    public class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (LOCAL_BROADCAST.equals(intent.getAction())) {
                    switch (intent.getIntExtra("action", 1)) {
                        case 1:
                            courseDetailsModel = new Gson().fromJson(intent.getStringExtra("courseInfo"), CourseDetailsModel.class);
                            tvTitle.setText(courseDetailsModel.getData().getCourse().getTitle());
                            tvShortTitle.setText(courseDetailsModel.getData().getCourse().getShort_title());
                            if (intent.getIntExtra("position", -1) == -1) {
                                Toast.makeText(context, "找不到语音课程", Toast.LENGTH_SHORT).show();
                            } else {
                                mPosition = 0;
                                chooseId = courseDetailsModel.getData().getClass_list().get(0).getId();
                                mDuration = getDuration(0);
                                getData(1);
                            }
                            break;
                        case 2://课程目录点击事件
                            mPosition = intent.getIntExtra("position", 1);
                            chooseId = courseDetailsModel.getData().getClass_list().get(mPosition).getId();
                            mDuration = getDuration(mPosition);
                            getData(2);
                            break;
                        case 3://CoursePlaySpeedSetDialog 倍速
                            switch (intent.getStringExtra("speed")) {
                                case "0.7x":
                                    speed = 0.7f;
                                    ivBeisu.setImageResource(R.mipmap.course_07beisu);
                                    break;
                                case "正常倍速":
                                    speed = 1.0f;
                                    ivBeisu.setImageResource(R.mipmap.course_1beisu);
                                    break;
                                case "1.25x":
                                    speed = 1.25f;
                                    ivBeisu.setImageResource(R.mipmap.course_125beisu);
                                    break;
                                case "1.5x":
                                    speed = 1.5f;
                                    ivBeisu.setImageResource(R.mipmap.course_15beisu);
                                    break;
                                case "2.0x":
                                    speed = 2.0f;
                                    ivBeisu.setImageResource(R.mipmap.course_2beisu);
                                    break;
                            }
                            aliyunVodPlayer.setSpeed(speed);
                            break;
                        case 4://定时

                            break;
                        case 5://目录dialog,已选中项改变状态
                            isPlaying = intent.getBooleanExtra("isPlaying", true);
                            if (isPlaying) {
                                ivPlay.setImageResource(R.mipmap.course_pause);
                                // 开始播放。
                                aliyunVodPlayer.start();
                            } else {
                                ivPlay.setImageResource(R.mipmap.course_play_fm);
                                aliyunVodPlayer.pause();
                            }
                            break;
                        case 6://目录dialog
                            mPosition = intent.getIntExtra("position", 1);
                            chooseId = courseDetailsModel.getData().getClass_list().get(mPosition).getId();
                            mDuration = getDuration(mPosition);
                            isPlaying = intent.getBooleanExtra("isPlaying", true);
                            getData(2);
                            break;
                    }
                }
            } catch (Exception e) {
            }
        }
    }

    private long getDuration(int i) {
        int duration = 0;
        String file_info = courseDetailsModel.getData().getClass_list().get(0).getFile_info();
        if (file_info != null && !"".equals(file_info)) {
            try {
                JSONObject mJsonObject = new JSONObject(file_info);
                duration = mJsonObject.getInt("duration");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            duration = 0;
        }
        return duration * 1000;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_course_details_fm;
    }

    @Override
    protected void initView() {
        setTitleText("电台");
        id = getIntent().getIntExtra("id", 0);
        registerMessageReceiver();
        tvTitle = findViewById(R.id.tvTitle);
        tvShortTitle = findViewById(R.id.tvShortTitle);
        ivPlay = findViewById(R.id.ivPlay);
        ivDaotui = findViewById(R.id.ivDaotui);
        ivQianjin = findViewById(R.id.ivQianjin);
        ivXunhuan = findViewById(R.id.ivXunhuan);
        ivBeisu = findViewById(R.id.ivBeisu);
        ivDingshi = findViewById(R.id.ivDingshi);
        ivList = findViewById(R.id.ivList);
        ivWengao = findViewById(R.id.ivWengao);
        tvPlayTime = findViewById(R.id.tvPlayTime);
        tvTotalTime = findViewById(R.id.tvTotalTime);
        seekBar = findViewById(R.id.seekBar);
        mTabLayout = findViewById(R.id.tabs);
        mViewPager = findViewById(R.id.viewpager);
        ivPlay.setOnClickListener(this);
        ivDaotui.setOnClickListener(this);
        ivQianjin.setOnClickListener(this);
        ivXunhuan.setOnClickListener(this);
        ivBeisu.setOnClickListener(this);
        ivDingshi.setOnClickListener(this);
        ivList.setOnClickListener(this);
        ivWengao.setOnClickListener(this);
        tvPlayTime.setText(TimeFormater.formatMs(0));
        seekBar.setOnSeekBarChangeListener(seekBarChangeListener);
        fmFragment = CourseDetailsFMFragment.newInstance(id);
        hudongFragment = CourseDetailsHudongFragment.newInstance(id);
        mAdapter = new CoursePagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        initPlayer();
    }

    class CoursePagerAdapter extends FragmentPagerAdapter {

        public CoursePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            if (i == 0) {
                return fmFragment;
            } else if (i == 1) {
                return hudongFragment;
            }
            return null;
        }

        @Override
        public int getCount() {
            return mTitle.length;
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return mTitle[position];
        }
    }

    private void getData(final int from) {
        new HttpRequest(getContext()).doGet(UrlConstants.course_play_auth + String.valueOf(chooseId), "", new HashMap(), CourseDetailsPlayAuthModel.class, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                if (result instanceof CourseDetailsPlayAuthModel) {
                    model = (CourseDetailsPlayAuthModel) result;
                    preparePlay(from);
                }
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        aliyunVodPlayer.stop();
        localBroadcastManager.unregisterReceiver(myBroadcastReceiver);
    }

    @Override
    protected int getTitleBarType() {
        return TITLEBAR_DEFAULT;
    }

    //seekbar的滑动监听
    SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                //这里是用户拖动，直接设置进度就行，
                // 无需去updateAllViews() ， 因为不影响其他的界面。
                tvPlayTime.setText(TimeFormater.formatMs(progress));
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            aliyunVodPlayer.seekTo(seekBar.getProgress());
        }
    };

    private void initPlayer() {
        aliyunVodPlayer = AliPlayerFactory.createAliPlayer(getContext());
        aliyunVodPlayer.setOnCompletionListener(new IPlayer.OnCompletionListener() {
            @Override
            public void onCompletion() {
                //播放完成事件
                switch (loop) {//1单曲循环,2列表循环,0顺序播放
                    case 0:
                        if (mPosition + 1 < courseDetailsModel.getData().getClass_list().size()) {
                            mPosition++;
                            chooseId = courseDetailsModel.getData().getClass_list().get(mPosition).getId();
                            mDuration = getDuration(mPosition);
                            updateMulu();
                            getData(2);
                        } else {
                            isPlaying = false;
                            ivPlay.setImageResource(R.mipmap.course_play_fm);
                        }
                        break;
                    case 1:
                        break;
                    case 2:
                        if (mPosition + 1 < courseDetailsModel.getData().getClass_list().size()) {
                            mPosition++;
                        } else {
                            mPosition = 0;
                        }
                        chooseId = courseDetailsModel.getData().getClass_list().get(mPosition).getId();
                        mDuration = getDuration(mPosition);
                        updateMulu();
                        getData(2);
                        break;
                }
            }
        });
        aliyunVodPlayer.setOnErrorListener(new IPlayer.OnErrorListener() {
            @Override
            public void onError(ErrorInfo errorInfo) {
                //出错事件
            }
        });
        aliyunVodPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
            @Override
            public void onPrepared() {
                //准备成功事件
            }
        });
        aliyunVodPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
            @Override
            public void onInfo(InfoBean infoBean) {
                if (infoBean.getCode() == InfoCode.AutoPlayStart) {
                    //自动播放开始,需要设置播放状态
                } else if (infoBean.getCode() == InfoCode.BufferedPosition) {
                    //更新bufferedPosition
                    mVideoBufferedPosition = infoBean.getExtraValue();
                    seekBar.setSecondaryProgress((int) mVideoBufferedPosition);
                } else if (infoBean.getCode() == InfoCode.CurrentPosition) {
                    //更新currentPosition
                    mCurrentPosition = infoBean.getExtraValue();
                    seekBar.setProgress((int) mCurrentPosition);
                    tvPlayTime.setText(TimeFormater.formatMs(mCurrentPosition));
                }
            }
        });
        aliyunVodPlayer.setOnLoadingStatusListener(new IPlayer.OnLoadingStatusListener() {
            @Override
            public void onLoadingBegin() {
                //缓冲开始。
            }

            @Override
            public void onLoadingProgress(int percent, float kbps) {
                //缓冲进度
            }

            @Override
            public void onLoadingEnd() {
                //缓冲结束
            }
        });
    }

    /**
     * 一章播放完，播放下一章，更新目录
     */
    private void updateMulu() {
        fmFragment.muluAdapter.setClickPosition(chooseId);
        fmFragment.muluAdapter.notifyDataSetChanged();
    }

    private void preparePlay(int from) {
        VidAuth vidAuth = new VidAuth();
        vidAuth.setPlayAuth(model.getData().getPlayAuth());
        vidAuth.setVid(model.getData().getVideoMeta().getVideoId());
        //设置播放源
        aliyunVodPlayer.setDataSource(vidAuth);
        //准备播放
        aliyunVodPlayer.prepare();
        seekBar.setMax((int) mDuration);
        tvTotalTime.setText(TimeFormater.formatMs(mDuration));
        switch (from) {
            case 1:
                isPlaying = false;
                ivPlay.setImageResource(R.mipmap.course_play_fm);
                break;
            case 2:
                isPlaying = true;
                ivPlay.setImageResource(R.mipmap.course_pause);
                // 开始播放。
                aliyunVodPlayer.start();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivPlay:
                switchPlayerState();
                break;
            case R.id.ivDaotui:
                mCurrentPosition = mCurrentPosition - 15000;
                if (mCurrentPosition > 0) {
                    aliyunVodPlayer.seekTo(mCurrentPosition);
                } else {
                    mCurrentPosition = 0;
                    aliyunVodPlayer.seekTo(0);
                }
                break;
            case R.id.ivQianjin:
                mCurrentPosition = mCurrentPosition + 15000;
                if (mCurrentPosition > mDuration) {
                    mCurrentPosition = mDuration;
                    aliyunVodPlayer.seekTo(mCurrentPosition);
                } else {
                    aliyunVodPlayer.seekTo(mCurrentPosition);
                }
                break;
            case R.id.ivXunhuan://1单曲循环,2列表循环,0顺序播放
                if (loop == 0) {
                    loop = 1;
                    aliyunVodPlayer.setLoop(true);
                    ivXunhuan.setImageResource(R.mipmap.course_loop_danqu);
                } else if (loop == 1) {
                    loop = 2;
                    aliyunVodPlayer.setLoop(false);
                    ivXunhuan.setImageResource(R.mipmap.course_loop_list);
                } else if (loop == 2) {
                    loop = 0;
                    aliyunVodPlayer.setLoop(false);
                    ivXunhuan.setImageResource(R.mipmap.course_shunxu);
                }
                break;
            case R.id.ivBeisu:
                CoursePlaySpeedSetDialog speedSetDialog = new CoursePlaySpeedSetDialog(getContext(), speed);
                speedSetDialog.show(getSupportFragmentManager());
                break;
            case R.id.ivDingshi:
                CoursePlayTimingSetDialog timingSetDialog = new CoursePlayTimingSetDialog(getContext(), "不开启");
                timingSetDialog.show(getSupportFragmentManager());
                break;
            case R.id.ivList:
                CoursePlayMuluSetDialog muluSetDialog = new CoursePlayMuluSetDialog(getContext(), chooseId, isPlaying, courseDetailsModel.getData().getClass_list());
                muluSetDialog.show(getSupportFragmentManager());
                break;
            case R.id.ivWengao:
                CourseDetailsFMWengaoActivity.actionStart(getContext(), id, new Gson().toJson(courseDetailsModel));
                break;
        }
    }

    /**
     * 切换播放状态。播放按钮之后的操作
     */
    private void switchPlayerState() {
        if (isPlaying) {
            aliyunVodPlayer.pause();
            ivPlay.setImageResource(R.mipmap.course_play_fm);
        } else {
            // 开始播放。
            aliyunVodPlayer.start();
            ivPlay.setImageResource(R.mipmap.course_pause);
        }
        isPlaying = !isPlaying;
    }
}
